package com.it.schoolbookshop_back.service.impl;

import com.it.schoolbookshop_back.mapper.MoneyMapper;
import com.it.schoolbookshop_back.service.MoneyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户资金服务实现类
 */
@Slf4j
@Service
public class MoneyServiceImpl implements MoneyService {

    @Autowired
    private MoneyMapper moneyMapper;

    /**
     * 用户余额充值
     * @param userId 用户ID
     * @param amount 充值金额
     * @return 充值是否成功
     * @throws IllegalArgumentException 如果充值金额小于等于0
     */
    @Override
    @Transactional
    public boolean recharge(Integer userId, Double amount) throws IllegalArgumentException {
        // 验证充值金额必须大于0
        if (amount == null || amount <= 0) {
            throw new IllegalArgumentException("充值金额必须大于0");
        }

        try {
            // 获取当前余额
            Double currentBalance = moneyMapper.getBalanceByUserId(userId);
            
            // 如果用户余额为空，设置为0
            if (currentBalance == null) {
                currentBalance = 0.0;
            }
            
            // 计算新余额
            Double newBalance = currentBalance + amount;
            
            // 更新余额
            int rows = moneyMapper.updateBalance(userId, newBalance);
            
            log.info("用户{}充值{}元，更新前余额{}元，更新后余额{}元", userId, amount, currentBalance, newBalance);
            
            return rows > 0;
        } catch (Exception e) {
            log.error("用户{}充值{}元失败: {}", userId, amount, e.getMessage(), e);
            throw e;
        }
    }

    /**
     * 获取用户余额
     * @param userId 用户ID
     * @return 用户余额
     */
    @Override
    public Double getUserBalance(Integer userId) {
        return moneyMapper.getBalanceByUserId(userId);
    }
}
